import React, {useEffect, useState} from 'react';
import {
    Select,
    message
} from "antd";
import {connect} from "react-redux";
import axios from "axios";
import axiosConfig from "../../utils/axios.config";

const {Option} = Select
const SearchTag = (props) => {
    const {setTags,defaultValue} = props

    const [tags,setOwnTags] = useState([])
    const [selectValue,setSelectValue] = useState([])
    function onChange (value){
        if(value.length>2){
            message.warn('最多只能选择两个标签!')
            setSelectValue(selectValue.slice(0,2))
            if(setTags) setTags(selectValue.slice(0,2))
        }else {
            setSelectValue(value)
            if(setTags) setTags(value)
        }
    }

    function getTags(){
        axios({
            url:'/home/getBasicInfo',
            baseURL:axiosConfig.baseURL,
            method:'GET'
        }).then(response=>{
            setOwnTags(response.data.tags)
        }).catch(err=>{
            console.log(err)
        })
    }

    useEffect(()=>{
        setSelectValue(defaultValue)
        getTags()
    },[])

    return (
        <Select
            mode="multiple"
            allowClear
            style={{ width: '300px' }}
            showSearch
            placeholder="Select a Tag"
            optionFilterProp="children"
            filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            value={selectValue}
            onChange={(value)=>{onChange(value)}}
        >
            {
                tags.map(item=>{
                    return <Option key={item}>{item}</Option>
                })
            }
        </Select>)
}



export default connect(
    (state)=>{
        return{
            tags:state.editorOneTag
        }
    },
    null
)(SearchTag);